package com.ddf.lucky.controller;

import com.ddf.pluto.utils.InviteUtils;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.tool.MoneyFund;
import com.ddf.publics.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.security.Principal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@RequestMapping(value = "/specimens")
public class specimensController {

    /**
     * 放标
     */
    @Resource
    SpecimensService specimensService;
    /**
     * 投资
     */
    @Resource
    BidService bidService;
    /**
     * 用户信息
     */
    @Resource
    UserInfoService userInfoService;
    /**
     * 资金
     */
    @Resource
    FundService fundService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private PayPwdService payPwdService;

    @Autowired
    private UserService userService;
    @Autowired
    private ConversionService conversionService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private InviteUtils inviteUtils;

    /**
     * 去到首页
     * @return
     */
    @RequestMapping(value = "/toIndex")
    public String toIndex(){
        return "index";
    }
    /**
     * (后台)分页查询放标列表
     * @param
     * @return
     */
    @RequestMapping(value = "/specimensList")
    @ResponseBody
    public Map specimensList(Integer page,Integer limit){
        if(page==null){
            page=1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        int size = specimensService.totalRows();
        List<Specimens> list = specimensService.queryAllByLimit(offset,limit);
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","提示");
        map.put("count",size);
        map.put("data",list);
        return map;
    }

    @RequestMapping(value = "/tospecimensList")
    public String specimensList(){
        return "manage_pages/specimensList";
    }

    /**
     * (后台)去到新增放标页面
     * @return
     */
    @RequestMapping(value = "/toSpecimensadd")
    public String toSpecimensadd(){
        return "manage_pages/specimensAdd";
    }

    /**
     * (后台)新增放标操作
     * @param specimens
     * @return
     */
    @RequestMapping(value = "/specimensAdd")
    public String specimensAdd(Specimens specimens){
        specimens.setPlan("0");
        specimensService.insert(specimens);
        return "redirect:/specimens/tospecimensList";
    }

    /**
     * (后台)根据ID查出数据
     * @param sid
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/selectId/{sid}")
    public String selectId(@PathVariable int sid, ModelMap modelMap){
        Specimens specimens = specimensService.queryById(sid);
        modelMap.addAttribute("spe",specimens);
        return "manage_pages/specimensUpdate";
    }

    /**
     * (后台)修改操作
     * @param specimens
     * @return
     */
    @RequestMapping(value = "/speUpdate")
    public String selectId(Specimens specimens){
        specimensService.update(specimens);
        return "redirect:/specimens/tospecimensList";
    }

    /**
     * (后台)删除操作
     * @param sid 获取该数据的ID
     * @return
     */
    @RequestMapping(value = "/speDelete/{sid}")
    public String speDelete(@PathVariable int sid){
        specimensService.deleteById(sid);
        return "redirect:/specimens/tospecimensList";
    }

    /**
     * 前台(我要投资页面)
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/toMytz")
    public String toMytz(ModelMap modelMap){
        List<Specimens> list = specimensService.queryAllList();
        modelMap.addAttribute("spe",list);
        return "pages/mytz";
    }

    /**
     * 前台(去到立即投资页面)
     * @param sid   放标编号
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/toNowtz")
    public String toNowtz(int sid, ModelMap modelMap, Principal principal, Integer page, Integer limit ){
        int size = bidService.qtTotalRows(sid);
        if(page==null){
            page=1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        User user = loginService.queryByPhone(principal.getName());
        //资金
        int uid = user.getId();
        UserInfo userInfo = userInfoService.userInfoList(uid);
        //放标
        Specimens specimens = specimensService.queryById(sid);
        //查询该标的投资
        List<Map> list = bidService.bidList(sid,offset,limit);
        Float m = bidService.Zmoney(sid);
        if(m==null){
            double surplus_money =specimens.getAllmoney();
            modelMap.addAttribute("surplus_money",surplus_money);
            //计算出该标的总投资(百分比)
            NumberFormat nf = NumberFormat.getPercentInstance();
            nf.setMinimumFractionDigits(2);
            String m3 =nf.format(0);
            specimens.setPlan(m3);
            specimensService.update(specimens);
            modelMap.addAttribute("surplus_money",surplus_money);
            modelMap.addAttribute("allTouzi",m3);
        }else {
            double surplus_money =specimens.getAllmoney()-m;
            //计算出百分比
            Float m2 = m/specimens.getAllmoney();
            NumberFormat nf = NumberFormat.getPercentInstance();
            nf.setMinimumFractionDigits(2);
            String m3 =nf.format(m2);
            specimens.setPlan(m3);
            specimensService.update(specimens);
            modelMap.addAttribute("surplus_money",surplus_money);
            modelMap.addAttribute("allTouzi",m3);
        }
        int type = specimens.getTypes();

        modelMap.addAttribute("qtspe",specimens);
        modelMap.addAttribute("page",size);
        modelMap.addAttribute("userinfo",userInfo);
        modelMap.addAttribute("sid",sid);
        modelMap.addAttribute("type",type);

        if(type==Constant.SIGN_TYPE2){
            return "pages/mypromptlyTouzi";
        }else {
            return "pages/mypromptlyTouziHq";
        }
    }

    @RequestMapping(value = "/eacharts/{sid}")
    @ResponseBody
    public List<Map> eacharts(@PathVariable("sid") int sid){
        List<Map> eachart = bidService.sbEacharts(sid);

        Vector list = new Vector();

        Map<String,Object> map = new ConcurrentHashMap<>();
        map.put("name","0-500");
        map.put("value",eachart.get(0).get("count(*)"));
        list.add(map);

        Map<String,Object> map1 = new ConcurrentHashMap<>();
        map1.put("name","500-1000");
        map1.put("value",eachart.get(1).get("count(*)"));
        list.add(map1);

        Map<String,Object> map2 = new ConcurrentHashMap<>();
        map2.put("name","1000-1500");
        map2.put("value",eachart.get(2).get("count(*)"));
        list.add(map2);

        Map<String,Object> map3 = new ConcurrentHashMap<>();
        map3.put("name","1500-2000");
        map3.put("value",eachart.get(3).get("count(*)"));
        list.add(map3);

        Map<String,Object> map4 = new ConcurrentHashMap<>();
        map4.put("name","2000-2500");
        map4.put("value",eachart.get(4).get("count(*)"));
        list.add(map4);

        Map<String,Object> map5 = new ConcurrentHashMap<>();
        map5.put("name",">2500");
        map5.put("value",eachart.get(5).get("count(*)"));
        list.add(map5);
        return list;
    }
    @RequestMapping(value = "/toNowtzfenye")
    @ResponseBody
    public List<Map> toNowtzfenye(int sid, Integer page, Integer limit){
        int size = bidService.qtTotalRows(sid);
        if(page==null){
            page=1;
        }
        if(limit==null){
            limit=10;
        }
        int offset = (page-1)*limit;
        //查询该标的投资
        List<Map> list = bidService.bidList(sid,offset,limit);
        return list;
    }
    /**
     *(前台)新增投资
     * @param bid
     * @return
     */
    @RequestMapping(value = "/tzAdd")
    @ResponseBody
    public synchronized String tzAdd(Bid bid,Principal principal,int startmoney,int sid,ModelMap modelMap,String password,Integer coupon_money,Integer couponId) throws ParseException {
        if(coupon_money == null){
            coupon_money = 0;
        }
        User user = loginService.queryByPhone(principal.getName());
        int uid = user.getId();

        UserInfo userInfo = userInfoService.userInfoList(uid);
        Specimens specimens = specimensService.queryById(sid);
        Float moneys = bidService.Zmoney(sid);
        if(moneys==null){
            moneys=0f;
        }
        Double money = bid.getMoney();

        switch (payPwdService.payPwd(uid,password)){
            case Constant.PAY_LOCK:
                return "7";
            case Constant.PAY_NO:
                return "6";
        }
        bid.setInvestor(user.getId());
        bid.setInvestorIph(user.getPhone());
        bid.setInvestmentTime(new Date());

        bid.setEstimateMoney(Double.valueOf(165));
        bid.setState(1);

        //资金
        Fund fund = new Fund();
        double s = bid.getMoney();
        fund.setFundAmunt((float)s);
        fund.setFundPost(MoneyFund.FUND_INVEST);
        fund.setUId(user.getId());
        fundService.insert(fund);

        //用户信息表的资金减少相对应的金额
        double m = userInfo.getMoney()-money+coupon_money;
        userInfo.setMoney((float)m);
        userInfoService.update(userInfo);

        //给当前登录的用户添加积分
        userService.userAddPoint(user,Constant.INVAESTMENT_POTINS);
        //把获得的积分记录在数据库中
        conversionService.userIntegralRecord(user,Constant.INVAESTMENT_POTINS,Constant.INVESTMENT_ACQUISITION);

        //使用优惠券后状态改变
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setCouponState(Constant.USED);
        userCoupon.setId(couponId);
        userCouponService.update(userCoupon);

        //剩余可投金额
        double surplus_money =specimens.getAllmoney()-money;
        specimens.setAllmoney((int) surplus_money);

        modelMap.addAttribute("surplus",surplus_money);
        int seconds_remaining = 0;
        if(specimens.getTypes()==2){
            //预期可收回金额  理财本金×预期收益率×理财期限/365。
            Float xaoshu = Float.valueOf(specimens.getExpectedyield());
            Double backMoney = bid.getMoney()*xaoshu/100*specimens.getInvesthorizon()/365;
            bid.setEstimateMoney(backMoney);

            //收回时间
            Calendar cld = Calendar.getInstance();
            cld.set(Calendar.YEAR, new Date().getYear()+1900);
            cld.set(Calendar.MONDAY,new Date().getMonth());
            cld.set(Calendar.DATE,new Date().getDate());

            //调用Calendar类中的add()，增加时间量(天数)
            cld.add(Calendar.DATE, specimens.getInvesthorizon());
            //秒数=到期时间-投资时间/1000
            seconds_remaining  = (int) ((cld.getTime().getTime()-new Date().getTime())/1000);
            Date time = cld.getTime();
            bid.setRecoveryTime(time);
        }
        if(specimens.getTypes()==1){
            //每天可赚金额  理财本金×预期收益率×理财期限/365。
            Float xaoshu = Float.valueOf(specimens.getExpectedyield());
            Double backMoney = bid.getMoney()*xaoshu/100*1/365;
            bid.setHqmoney_day(backMoney);
            bid.setEstimateMoney(0.0);
        }
        //判断是否可以用新手标（小于3或等于3的将加上新手标）
        int size=bidService.count(bid.getMarkId(),uid);
        if(size<3){
            Float xaoshu2 = Float.valueOf(specimens.getExpectedyield()+specimens.getNewStandard());
            Double backMoney2 = bid.getMoney()*xaoshu2/100*specimens.getInvesthorizon()/365;
            bid.setEstimateMoney(backMoney2);
        }
        bid = bidService.insert(bid);
        inviteUtils.inviteUtils(bid);
        if(specimens.getTypes()==Constant.SIGN_TYPE2){
            //存入redis
            redisUtil.set("bid:"+bid.getBidId(),"",30);
        }
        return "1";
    }

    @RequestMapping(value = "/sh/{bidId}")
    @ResponseBody
    public String sh(@PathVariable("bidId") int bidId,Principal principal){
        Bid bid1 = bidService.queryById(bidId);
        User user = loginService.queryByPhone(principal.getName());
        int uid = user.getId();
        UserInfo userInfo = userInfoService.userInfoList(uid);
        bid1.setState(2);
        bid1.setRecoveryTime(new Date());

        userInfo.setMoney((float) (userInfo.getMoney()+bid1.getMoney()+bid1.getEstimateMoney()));
        userInfoService.update(userInfo);
        bidService.update(bid1);

        return "10";
    }


    @RequestMapping(value = "/cz")
    @ResponseBody
    public String cz(Principal principal,Bid bid,int startmoney,int sid){
        User user = loginService.queryByPhone(principal.getName());
        Float moneys = bidService.Zmoney(sid);
        if(moneys==null){
            moneys=0f;
        }

        Double money = bid.getMoney();
        Specimens specimens = specimensService.queryById(sid);
        UserInfo userInfo = userInfoService.userInfoList(user.getId());
        if(money>userInfo.getMoney()){
            return "0";
        }
        if(money<startmoney){
            return "2";
        }
        if (money > specimens.getAllmoney() - moneys){
            return "3";
        }
        if(userInfo.getPayPwd().equals("")||userInfo.getPayPwd()==null){
            return "4";
        }
        userInfo.getPayPwd();
        return "5";
    }
    /**
     * (后台)去到投资列表
     * @return
     */
    @RequestMapping(value = "/totzList")
    public String totzList(){
        return "manage_pages/touziList";
    }

    /**
     * (后台)分页查询投资列表
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "/touziList")
    @ResponseBody
    public Map touziList(Integer page,Integer limit){
        if(page==null){
            page=1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        int size = bidService.totalRows();
        List<Map> list = bidService.queryAllByLimit(offset,limit);
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","提示");
        map.put("count",size);
        map.put("data",list);
        return map;
    }

    /**
     * (后台)删除投资列表
     * @param bidId
     * @return
     */
    @RequestMapping(value = "/DidDelete/{bidId}")
    public String DidDelete(@PathVariable int bidId){
        bidService.deleteById(bidId);
        return "redirect:/specimens/tospecimensList";
    }

}